package com.twt.service;

import com.twt.Dao.MessageDao;
import com.twt.Dao.PickLakeDao;
import com.twt.Dao.ThrowLakeDao;
import com.twt.Dao.UserDao;
import com.twt.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

import com.twt.entity.lake;

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class PickLakeService {

    @Autowired
    private PickLakeDao pickLakeDao;
    @Autowired
    private MessageDao messageDao;

    /**
     * 捞湖仅查看
     *
     * @param username 参数封装
     * @return Result
     */

    public Result pickLakeView(String username) {
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        result.setMsg(null);
        Random random = new Random();
        int randomId;
        int bottleId;
        List<Integer> bottle = pickLakeDao.findBottle(username);
        if (bottle.size() == 0) {
            result.setMsg("当前没有瓶子可捞");
            return result;
        } else {
            randomId = random.nextInt(bottle.size());
            bottleId = bottle.get(randomId);
        }
        lake lake = pickLakeDao.findLakeById1(bottleId);
        pickLakeDao.insertWhoPicked(username, pickLakeDao.findNicknameByUsername(username), bottleId);
        result.setSuccess(true);
        result.setDetail(lake);
        result.setMsg("捞湖仅查看成功");
        return result;
    }


    /**
     * 捞湖
     *
     * @param username,bottleId 参数封装
     * @return Result
     */
    public Result pickLake(String username, int bottleId, String context) {
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        result.setMsg(null);
        lake lake = new lake();
        lake = pickLakeDao.findLakeById1(bottleId);//找湖里面的瓶子的内容
        pickLakeDao.insertPicked(bottleId, lake.getNickname(), lake.getUsername(), lake.getContext());
        pickLakeDao.insertThrowed(bottleId, pickLakeDao.findNicknameByUsername(username), username, lake.getContext());
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//设置日期格式
        String Time = df.format(new Date());// new Date()为获取当前系统时间
        messageDao.insertMessage(bottleId,lake.getUsername(),lake.getContext(),lake.getTime());
        messageDao.insertMessage(bottleId, username, context, Time);
        pickLakeDao.pickLake(bottleId);//删除湖里的瓶子
        result.setMsg("捞湖成功");
        result.setSuccess(true);
        return result;
    }
}
